local db = require("asyncsql4lua").postgres

local function connect(host, port, user, password, database)
    local inner_fn = coroutine.wrap(
        function()
            db:connect(host, port, user, password, database)
        end
    )
    while true do
        if inner_fn() == nil then 
            break
        end
    end
end

local function execute(sql)
    local inner_fn = coroutine.wrap(
        function()
            db:execute(sql)
        end
    )
    while true do
        if inner_fn() == nil then 
            break
        end
    end
end

local function query(sql)
    local res
    local inner_fn = coroutine.wrap(
        function()
            res = db:query(sql)
        end
    )
    while true do
        if inner_fn() == nil then
            break
        end
    end
    return res
end
-- Run database operations in a coroutine
local function main()
    connect(
        "localhost",
        5432,
        "postgres",
        "Password2025",
        "testdb"
    )
    
    -- Create table if not exists
    execute([[
    CREATE TABLE IF NOT EXISTS 
    users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER NOT NULL,
    email TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT NOW())
    ]])

    execute([[
        INSERT INTO 
        users
        (name, age, email)
        VALUES
        ('Li', 20, 'li@gmail.com'),
        ('Shang', 21, 'shang@email.com'),
        ('Wu', 30, 'wu@163.com')
    ]])


    local res = query("SELECT * FROM users")
    for _, user in pairs(res) do
        print(user.id, user.name, user.age, user.created_at)
    end
end
main()